package com.af.dao.pay.impl;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;

import com.af.common.GlobalVariables;
import com.af.common.Log4jXmlConfig;
import com.af.common.SignUtil;
import com.af.dao.pay.PaySendReqRes;

public class WebSocket {

	Logger LOG = Log4jXmlConfig.getInstance().returnLogger(WebSocket.class);
	private PaySendReqRes psr = null;
	/**
	 * 获取通信端的返回信息
	 * 
	 * @param params
	 * @return
	 * @throws Exception
	 */
	public void returnWebResponse(Map params) {
		System.out.println(JSONObject.fromObject(params));
		String postData = SignUtil.createSortLinkString(params);
		psr = new PaySendReqRes();
		psr.insertSendRequest(params);
		publicMethod(postData);
	}

	private void publicMethod(String postData) {
		HttpURLConnection httpURLConnection;
		StringBuilder sb = null;
		try {
			URL url = new URL(GlobalVariables.PAY_URL);
			httpURLConnection = (HttpURLConnection) url.openConnection();
			httpURLConnection.setDoOutput(true);
			httpURLConnection.setDoInput(true);
			httpURLConnection.setRequestMethod("POST");
			httpURLConnection.setConnectTimeout(10000);
			httpURLConnection.setReadTimeout(30000);
			httpURLConnection.connect();
			BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
					httpURLConnection.getOutputStream(), "UTF-8"));
			out.write(postData);
			System.out.println(postData);
			out.flush();
			out.close();
			BufferedReader in = new BufferedReader(new InputStreamReader(
					(InputStream) httpURLConnection.getInputStream()));
			in.close();
			httpURLConnection.disconnect();
		} catch (MalformedURLException e) {
			LOG.error(e.getMessage());

			LOG.error(postData);

		} catch (ProtocolException e) {

			LOG.error(e.getMessage());

			LOG.error(postData);
			
		} catch (UnsupportedEncodingException e) {
			
			LOG.error(e.getMessage());

			LOG.error(postData);
			
		} catch (IOException e) {
			e.printStackTrace();
			LOG.error(e.getMessage());

			LOG.error(postData);
			
		}
	}
}
